﻿using Mono.Data.Sqlite;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.UI;

public class AnswerCtl : MonoBehaviour {
    public static AnswerCtl s_Instance;
    public class Question
    {
        public int ID;
        public int Type;
        public string stem;
        public string Pic_Path;

        public Question(int id,int type,string stem,string pic_path) {
            this.ID = id;
            this.Type = type;
            this.stem = stem;
            this.Pic_Path = pic_path;
        }
    }
    public List<Question> m_QuestionList = new List<Question>();
    public int m_QuestionIndexNow;
    public Text m_NumberText, m_StemText,m_TypeText;
    public Image m_InputImg;
    public List<AnswerOption> m_OptionNowList = new List<AnswerOption>();
    public AnswerOption m_AnswerOptionPrefab;
    public Transform m_OptionContent;
    public ToggleGroup m_ToggleGroup;
    public GameObject m_OptionPart, m_CompletionPart,m_EndPart;
    public InputField m_InputField;
    string time ;
    private string m_editorName;
    [SerializeField]
    private Stack<int> m_lastIndexStack = new Stack<int>();
    // Use this for initialization
    private void Awake() {
        s_Instance = this;
    }
    private void Start() {
        m_editorName = PlayerPrefs.GetString("EditorName", "555");
        time = DateTime.Now.ToString();
    }

    public void ShowQuestionNow() {
        
        Question question = m_QuestionList[m_QuestionIndexNow];
        m_NumberText.text = question.ID.ToString();
        m_StemText.text = question.stem;
        int type = question.Type;
        switch (type) {
            case 1:
                m_TypeText.text = "单选题";
                break;
            case 2:
                m_TypeText.text = "多选题";
                break;
            case 3:
                m_TypeText.text = "填空题";
                break;
        }
        if (question.Pic_Path.Length < 1) {
            m_InputImg.gameObject.SetActive(false);
            m_OptionPart.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -115.184f);
        } else {
            m_InputImg.gameObject.SetActive(true);
            m_OptionPart.GetComponent<RectTransform>().anchoredPosition = new Vector2(307f, -115.184f);
            LoadPicture(question.Pic_Path);
        }
        
        for (int i = 0;i<m_OptionContent.childCount;i++)
        {
            Destroy(m_OptionContent.GetChild(i).gameObject);
        }
        m_OptionNowList.Clear();

        if(question.Type == 3) {
            m_OptionPart.SetActive(false);
            m_CompletionPart.SetActive(true);
        } else {
            m_OptionPart.SetActive(true);
            m_CompletionPart.SetActive(false);
            string cmd = "select * from OPTION_TABLE where QID = " + question.ID.ToString();
            SqliteDataReader reader = SQLManager.s_Instance.ExecuteSQLCommand(cmd);
            if (reader != null) {
                DataTable dataTable = new DataTable();
                dataTable.Load(reader);
                if (dataTable.Rows.Count > 0) {
                    for (int i = 0; i < dataTable.Rows.Count; i++) {
                        AnswerOption option = Instantiate(m_AnswerOptionPrefab) as AnswerOption;
                        option.transform.SetParent(m_OptionContent);
                        option.transform.localScale = new Vector3(1f, 1f, 1f);
                        option.m_ID = (int)(long)dataTable.Rows[i]["ID"];
                        option.m_JumpID = (int)dataTable.Rows[i]["Jump_ID"];
                        option.m_Score = (int)dataTable.Rows[i]["Score"];
                        option.m_StemText.text = dataTable.Rows[i]["Stem"].ToString();
                        m_OptionNowList.Add(option);
                        if(question.Type == 1) {
                            option.m_Toggle.group = m_ToggleGroup;
                        }
                    }
                }
            }
        }

       
    }
    public void OnClickNextButton() {
        m_lastIndexStack.Push(m_QuestionIndexNow);
        print("push:" + m_QuestionIndexNow.ToString());
        Question question = m_QuestionList[m_QuestionIndexNow];
        if (question.Type == 3) {
            if (m_InputField.text.Length < 1) {
                return;
            }
        } else {
            if(question.Type == 2) {
                int c = 0;
                foreach (var item in m_OptionNowList) {
                    if (item.m_Toggle.isOn) {
                        c++;
                    }
                }
                if (c < 2) {
                    return;
                }
            } else {
                bool flag = false;
                foreach (var item in m_OptionNowList) {
                    if (item.m_Toggle.isOn) {
                        flag = true;
                    }
                }
                if (!flag) {
                    return;
                }
            }
            
        }
        InsertAnswer();
        int plus = 1;
        foreach (var item in m_OptionNowList)
        {
           if (item.m_JumpID != 0&&item.m_Toggle.isOn) {
                for(int i = 0; i < m_QuestionList.Count; i++) {
                      if(m_QuestionList[i].ID == item.m_JumpID) {
                         m_QuestionIndexNow = i;
                         plus = 0; 
                         break;
                       }
                    }
                }
            }
       

        m_QuestionIndexNow += plus;
        if (m_QuestionIndexNow>=m_QuestionList.Count) {
            //试卷结束
            string cmd = "select * from ANSWER_TABLE where PAPER_ID = " +AnswerMgr.s_Instance.m_AnswerExamPrefabNow.m_NumberText.text.Replace("试卷","").Replace(":","") + 
                " AND " + "USER_ID ='" + AnswerMgr.s_Instance.m_EditorName + "'"+
                " AND " + "TIME ='" + time + "'";
            SqliteDataReader reader = SQLManager.s_Instance.ExecuteSQLCommand(cmd);
            if (reader != null) {
                DataTable dataTable = new DataTable();
                dataTable.Load(reader);
                int score = 0;
                for (int i = 0; i < dataTable.Rows.Count; i++) {
                    score += (int)dataTable.Rows[i]["SCORE"];
                }
                AnswerMgr.s_Instance.m_ScoreText.text = score.ToString();
                reader.Close();
            }
            OnAnswerEnd();
            print("试卷结束");
        } else {
            ShowQuestionNow();
        }

    }
    public void OnClickPreQuestion() {
        if (m_lastIndexStack.Count > 0) {
            m_QuestionIndexNow = m_lastIndexStack.Pop();
            print("pop:" + m_QuestionIndexNow.ToString());
            ShowQuestionNow();
        }
    }

    public void OnAnswerEnd() {

        m_EndPart.SetActive(true);
    }
    void InsertAnswer() {
        int paper_id = int.Parse(AnswerMgr.s_Instance.m_AnswerExamPrefabNow.m_NumberText.text.Replace("试卷", "").Replace(":", ""));
        string userid = m_editorName;
        string optionChoosed = "";
        int score = 0;
        foreach(var item in m_OptionNowList) {
            if (item.m_Toggle.isOn) {
                optionChoosed += item.m_ID.ToString() + "_";
                score += item.m_Score;
            }
            
        }
        if (optionChoosed.Length > 0) {
            optionChoosed = optionChoosed.Substring(0, optionChoosed.Length - 1);
        }
        string fillblank = m_InputField.text;
        int type = m_QuestionList[m_QuestionIndexNow].Type;
        int qid = m_QuestionList[m_QuestionIndexNow].ID;
        string cmd = "INSERT INTO ANSWER_TABLE VALUES ('" +
            paper_id + "','" +
            userid + "','" +
            optionChoosed + "','" +
            fillblank + "','" +
            score.ToString() + "','" +
            type.ToString() + "','" +
            time + "','" +
            qid.ToString() + "')";
        SqliteDataReader reader = SQLManager.s_Instance.ExecuteSQLCommand(cmd);
        m_InputField.text = "";
    }


    void LoadPicture(string path) {
        if (path.Length < 1) {
            return;
        }
        StartCoroutine(Load(path));
    }
    IEnumerator Load(string path) {
        WWW www = new WWW("file:///" + path);
        yield return www;

        while (!www.isDone) {

        }
        if (www.error != null) {
            print(www.error);
            m_InputImg.sprite = null;
        } else {
            Texture2D texture = www.texture;
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            if (texture.width > texture.height) {
                m_InputImg.rectTransform.sizeDelta = new Vector2(600f, (float)texture.height / (float)texture.width * 600f);
            } else {
                m_InputImg.rectTransform.sizeDelta = new Vector2((float)texture.width / (float)texture.height * 600f, 600f);
            }
            m_InputImg.sprite = sprite;
        }

    }
}
